package org.esprit.ocm.client.ui.ec2;

import java.util.ArrayList;
import java.util.List;

import org.esprit.ocm.client.model.ec2.datasource.InstanceLocalDS;
import org.esprit.ocm.client.rpc.ec2.ImageService;
import org.esprit.ocm.client.rpc.ec2.ImageServiceAsync;
import org.esprit.ocm.dto.ec2.impl.InstanceDescriptionDto;
import org.esprit.ocm.dto.impl.AwsCredentialsDto;
import org.esprit.ocm.dto.impl.ServerDto;
import org.esprit.ocm.dto.impl.UserDto;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.viewer.DetailViewer;

public class InstanceZone extends SectionStack {

	private final ImageServiceAsync	imageService	= GWT.create(ImageService.class);

	private DataSource				ds;
	private ListGrid				grid;
	private DetailViewer			details;

	public InstanceZone(final ServerDto server, final AwsCredentialsDto credentials, final UserDto user) {

		getData(server, credentials);

		setVisibilityMode(VisibilityMode.MULTIPLE);
		setHeaderHeight(20);

		// DataSource instanceDataSource = InstanceLocalDS.getInstance();

		// creer instanceSection
		SectionStackSection instanceSection = new SectionStackSection("Instance List");
		instanceSection.setExpanded(true);
		addSection(instanceSection);

		// creer instanceGrid
		grid = new ListGrid();

		// instanceGrid.setShowFilterEditor(true);
		grid.setFilterOnKeypress(true);
		grid.setAutoFetchData(true);

		// creer instancetoolstrip
		ToolStrip instanceGridToolStrip = new ToolStrip();
		instanceGridToolStrip.setWidth100();
		instanceGridToolStrip.addFill();

		// ajouter toolstrip a instanceSection
		instanceSection.addItem(instanceGridToolStrip);

		Img filter = new Img("filter.png", 15, 15);

		// creer filterButton
		final Button filterButtonOn = new Button("On");
		filterButtonOn.setWidth(25);
		filterButtonOn.setHeight(20);
		filterButtonOn.setShowRollOver(true);
		filterButtonOn.setShowDown(true);
		// filterButtonOn.setIcon("filter.png");
		filterButtonOn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(true);
				grid.setFilterOnKeypress(true);
			}
		});
		// creer filterButton
		final Button filterButtonOff = new Button("Off");
		filterButtonOff.setWidth(25);
		filterButtonOff.setHeight(20);
		filterButtonOff.setShowRollOver(true);
		filterButtonOff.setShowDown(true);
		// filterButtonOff.setIcon("filter.png");
		filterButtonOff.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(false);
				grid.setFilterOnKeypress(false);
			}
		});

		final Button rebootButton = new Button("Reboot");
		rebootButton.setShowRollOver(true);
		rebootButton.setShowDown(true);
		rebootButton.setIcon("reboot.png");
		rebootButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				ListGridRecord[] instanceIds = grid.getSelection();

				List<String> instanceId = new ArrayList<String>();

				for (ListGridRecord i : instanceIds) {

//					System.out.println("-->" + i.getAttribute("instanceId"));
					instanceId.add(i.getAttribute("instanceId"));
				}
				imageService.rebootInstance(instanceId, server, credentials, new AsyncCallback<Void>() {

					public void onSuccess(Void arg0) {

						SC.say("Reboot OK");
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub

					}
				});
			}
		});

		final Button refreshButton = new Button("Refresh");
		refreshButton.setShowRollOver(true);
		refreshButton.setShowDown(true);
		refreshButton.setIcon("interact.png");
		refreshButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SC.say("Refreshed");
				ds.destroy();
				getData(server, credentials);
				grid.redraw();
			}
		});

		final Button deleteButton = new Button("Terminate");
		deleteButton.setShowRollOver(true);
		deleteButton.setShowDown(true);
		deleteButton.setIcon("stop.png");
		deleteButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				ListGridRecord[] instanceIds = grid.getSelection();

				List<String> instanceId = new ArrayList<String>();

				for (ListGridRecord i : instanceIds) {

					System.out.println("-->" + i.getAttribute("instanceId"));
					instanceId.add(i.getAttribute("instanceId"));
				}
				// String instanceId =
				// grid.getSelectedRecord().getAttribute("id");
				imageService.stopInstance(instanceId, server, credentials, new AsyncCallback<Void>() {

					public void onSuccess(Void arg0) {

						SC.say("Stopped");
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub

					}
				});
			}
		});

		// ajouter le bouton
		instanceGridToolStrip.addMember(rebootButton);
		instanceGridToolStrip.addMember(deleteButton);
		instanceGridToolStrip.addMember(refreshButton);
		instanceGridToolStrip.addSpacer(10);
		instanceGridToolStrip.addMember(filter);
		instanceGridToolStrip.addSpacer(2);
		instanceGridToolStrip.addMember(filterButtonOn);
		instanceGridToolStrip.addMember(filterButtonOff);
		instanceGridToolStrip.addSpacer(5);

		/******************************/
		// grid.setShowRecordComponents(true);
		// grid.setShowRecordComponentsByCell(true);
		// grid.setShowAllRecords(true);
		/******************************/

		// affecter les fields de instanceGrid
		// ListGridField ownerField = new ListGridField("owner", "Owner");
		// ListGridField instanceField = new ListGridField("instanceID",
		// "Instance ID");
		// ListGridField emiField = new ListGridField("emi", "EMI");
		// ListGridField ekiField = new ListGridField("eki", "EKI");
		// ListGridField eriField = new ListGridField("eri", "ERI");
		// ListGridField stateField = new ListGridField("state", "State");
		// ListGridField groupField = new ListGridField("group", "Group");
		//
		// grid.setFields(ownerField, instanceField, emiField, ekiField,
		// eriField, stateField, groupField);
		// instanceGrid.setDataSource(instanceDataSource);

		// ajouter instanceGrid a instanceSection
		instanceSection.addItem(grid);

		// creer DetailinstanceSection

		details = new DetailViewer();
		// instanceDetails.setDataSource(instanceDataSource);
		details.setWidth100();
		details.setMargin(15);
		details.setEmptyMessage("Select something to view its details");

		// relation entre instancegrid et instancedtails
		grid.addRecordClickHandler(new RecordClickHandler() {
			public void onRecordClick(RecordClickEvent event) {
				Record[] rec = new Record[] { event.getRecord() };
				for (Record record : rec) {

					System.out.println(record.getAttribute("instanceID"));
				}

				details.setData(new Record[] { event.getRecord() });
			}
		});

		// detailsection
		SectionStackSection instanceDetailSection = new SectionStackSection("Instance Detail");
		instanceDetailSection.setExpanded(true);
		instanceDetailSection.addItem(details);
		addSection(instanceDetailSection);

		draw();
	}

	private void getData(ServerDto server, AwsCredentialsDto credentials) {

		imageService.listInstances(server, credentials, new AsyncCallback<List<InstanceDescriptionDto>>() {

			public void onSuccess(List<InstanceDescriptionDto> l) {

				for (InstanceDescriptionDto idd : l) {
					System.out.println("->" + idd.getImageId());
				}
			}

			public void onFailure(Throwable arg0) {

			}
		});

		imageService.listInstances(server, credentials, new AsyncCallback<List<InstanceDescriptionDto>>() {

			public void onSuccess(List<InstanceDescriptionDto> list) {

				for (InstanceDescriptionDto i : list) {
					System.out.println("**" + i.getImageId());
				}
				ds = InstanceLocalDS.getInstance(list);
				grid.setDataSource(ds);
				details.setDataSource(ds);

				ListGridField resId = new ListGridField("resId", "resId");
				ListGridField owner = new ListGridField("owner", "owner");
				ListGridField imageId = new ListGridField("imageId", "imageId");
				ListGridField instanceId = new ListGridField("instanceId", "instanceId");
				ListGridField privateDnsName = new ListGridField("privateDnsName", "privateDnsName");
				ListGridField dnsName = new ListGridField("dnsName", "dnsName");
				ListGridField groups = new ListGridField("groups", "groups");
				ListGridField keyName = new ListGridField("keyName", "keyName");
				ListGridField launchTime = new ListGridField("launchTime", "launchTime");
				ListGridField launchIndex = new ListGridField("launchIndex", "launchIndex");
				ListGridField availabilityZone = new ListGridField("availabilityZone", "availabilityZone");
				ListGridField kernelId = new ListGridField("kernelId", "kernelId");
				ListGridField ramdiskId = new ListGridField("ramdiskId", "ramdiskId");
				ListGridField state = new ListGridField("state", "state");
				ListGridField monitoring = new ListGridField("monitoring", "monitoring");

				grid.setFields(resId, owner, imageId, instanceId, privateDnsName, dnsName, groups, keyName, launchTime, launchIndex, availabilityZone, kernelId,
						ramdiskId, state, monitoring);

				// ListGridField idField = new ListGridField("id");
				// ListGridField manifestField = new ListGridField("manifest",
				// 400);
				// ListGridField stateField = new ListGridField("state");
				// ListGridField ownerField = new ListGridField("owner");
				// ListGridField visibilityField = new
				// ListGridField("visibility");
				// ListGridField architectureField = new
				// ListGridField("architecture");
				//
				// grid.setFields(idField, manifestField, stateField,
				// ownerField, visibilityField, architectureField);

			}

			public void onFailure(Throwable arg0) {

			}
		});
	}
}
